# main.py
# Application entry point, pywebview window creation and management, main logic loop / event orchestrator.
# Detailed implementation will follow based on design documents.
# Standard library imports
import logging

# Third-party imports
import webview

# Local application imports
from core import logic_executor
from api_interfaces.outer_api_bridge import PywebviewOuterApi

# Configure basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
logger = logging.getLogger(__name__)


def main_app():
    logger.info("LLM Chatroom Application - MVP - Initializing...")

    # 1. Start the logic executor (this will initialize all core services in a separate thread)
    logic_executor.start_logic_executor()
    logger.info("Logic executor started.")

    # 2. Create the API instance for pywebview
    # This instance will internally get its dependencies from the logic_executor
    api_instance = PywebviewOuterApi()
    logger.info("PywebviewOuterApi instance created.")
    
    # 3. Create and start the pywebview window
    logger.info("Creating pywebview window...")
    window = webview.create_window(
        "LLM Chatroom MVP",
        "ui/index.html",
        js_api=api_instance,
        width=1200,
        height=800
    )
    
    # webview.start() is a blocking call. It will run until the window is closed.
    # The `on_closed` event of the window can be used for cleanup if needed,
    # but here we'll do cleanup after webview.start() returns.
    try:
        logger.info("Starting pywebview event loop...")
        webview.start(debug=True) # Set debug=False for production
    finally:
        # 4. Clean up: This will run after the pywebview window is closed
        logger.info("Pywebview window closed. Stopping logic executor...")
        logic_executor.stop_logic_executor()
        logger.info("Logic executor stopped. Application finished.")

if __name__ == "__main__":
    main_app()
    # main_app() # Removed duplicate call for cleaner testing